/**
 * 
 */
package com.huxi.lang.local.support;

import static com.huxi.lang.local.DateUtils.DEFAULT_TO_DAY_FORMAT;
import static com.huxi.lang.local.DateUtils.DEFAULT_TO_SECOND_FORMAT;
import static com.huxi.lang.local.DateUtils.DEFAULT_TO_TIMESTAMP_FORMAT;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

/**
 * 日期与时间本地化接口快速实现（非线程安全）
 * 
 * @author jian.wu
 * @since 1.0
 * @version 1.0
 */
public class QuickDateContext extends AbstractDateContext {

	private SimpleDateFormat dateFormat;
	private SimpleDateFormat timestampFormat;
	private boolean milliseconds;

	public QuickDateContext(TimeZone timeZone, String dateFormat, String timestampFormat, boolean milliseconds) {
		super(timeZone);
		this.dateFormat = (SimpleDateFormat) createDateFormat(dateFormat != null ? dateFormat : DEFAULT_TO_DAY_FORMAT);
		this.timestampFormat = (SimpleDateFormat) createDateFormat(
				timestampFormat != null ? timestampFormat : DEFAULT_TO_TIMESTAMP_FORMAT);
		this.milliseconds = milliseconds;
	}

	public QuickDateContext(TimeZone timeZone, boolean milliseconds) {
		this(timeZone, DEFAULT_TO_DAY_FORMAT, milliseconds ? DEFAULT_TO_TIMESTAMP_FORMAT : DEFAULT_TO_SECOND_FORMAT,
				milliseconds);
	}

	public QuickDateContext(TimeZone timeZone) {
		this(timeZone, true);
	}

	@Override
	public SimpleDateFormat getDateFormat() {
		return dateFormat;
	}

	@Override
	public SimpleDateFormat getTimestampFormat() {
		return timestampFormat;
	}

	@Override
	public Timestamp currentTimestamp() {
		if (milliseconds) {
			return new Timestamp(System.currentTimeMillis());
		} else {
			long ts = Math.floorDiv(System.currentTimeMillis(), 1000) * 1000;
			return new Timestamp(ts);
		}
	}

	@Override
	public Calendar getCalendar() {
		return dateFormat.getCalendar();
	}

	@Override
	public long dayInMillis(long millis) {
		Calendar calendar = getCalendar();
		calendar.setTimeInMillis(millis);
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		return calendar.getTimeInMillis();
	}

}
